package apps.web.controller;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.commons.lang.RandomStringUtils;
import org.springframework.web.servlet.ModelAndView;
import org.springframework.web.servlet.view.RedirectView;

import webframe.common.dao.BaseUser;
import webframe.common.helper.AppConstant;
import webframe.common.helper.Code2NameHelper;
import webframe.common.helper.ControllerHelper;
import webframe.common.helper.FormatTransformHelper;
import apps.web.controller.base.MyBaseController;
import apps.web.model.Apply;
import apps.web.model.ApplyCensor;
import apps.web.model.Container;
import apps.web.model.ContainerCheck;
import apps.web.model.Decl;
import apps.web.model.EntUser;
import apps.web.model.Goods;
import apps.web.model.GoodsCheck;
import apps.web.model.GoodsSituation;
import apps.web.model.InspResultSum;
import apps.web.model.PassageBill;
import apps.web.model.SupervisePlan;
import apps.web.model.UploadFile;
import apps.web.model.User;
import apps.web.model.UserRightSpec;
import apps.web.model.UserRightType;
import apps.web.model.WoodPackCheck;

public class MultiViewController extends MyBaseController {
	// accessdenied
	public ModelAndView accessDenied(HttpServletRequest request, HttpServletResponse response) {
		return new ModelAndView("public/AccessDenied.jsp");
	}

	// home
	public ModelAndView home(HttpServletRequest request, HttpServletResponse response) {
		Map map = new HashMap();
		map.put("ip", request.getRemoteAddr());
		return new ModelAndView("Home.jsp", "map", map);
	}

	// menu
	public ModelAndView menu(HttpServletRequest request, HttpServletResponse response) {
		Map map = new HashMap();
		map.put("ip", request.getRemoteAddr());
		return new ModelAndView("Menu.jsp", "map", map);
	}

	// 打开修改用户密码
	public ModelAndView userModifyPassword(HttpServletRequest request, HttpServletResponse response) {
		BaseUser user = ControllerHelper.getUserBySession();
		Map map = new HashMap();
		map.put("user", user);
		return new ModelAndView("UserModifyPassword.jsp", "map", map);
	}

	public ModelAndView cIQUserView(HttpServletRequest request, HttpServletResponse response) {
		Long id = ((User) ControllerHelper.getUserBySession()).getId();
		Map map = new HashMap();
		map.put("user", getServiceContainer().getUserService().findCIQUserById(id));
		return new ModelAndView("CIQUserView.jsp", "map", map);
	}

	// // ciquser
	// 创建ciq用户
	public ModelAndView cIQUserCreate(HttpServletRequest request, HttpServletResponse response) {
		User r = new User();
		Map map = new HashMap();
		r.setUserType("1");
		map.put("user", r);
		return new ModelAndView("CIQUserEdit.jsp", "map", map);
	}

	// 编辑ciq用户
	public ModelAndView cIQUserEdit(HttpServletRequest request, HttpServletResponse response) {
		Long id = ControllerHelper.extractId(request);
		Map map = new HashMap();
		map.put("user", getServiceContainer().getUserService().findCIQUserById(id));
		return new ModelAndView("CIQUserEdit.jsp", "map", map);
	}

	// 删除ciq用户
	public ModelAndView cIQUserDelete(HttpServletRequest request, HttpServletResponse response) {
		Long id = ControllerHelper.extractId(request);
		getServiceContainer().getUserService().deleteCIQUser(id);
		return new ModelAndView(new RedirectView("CIQUserSearch.do"));
	}

	// ciq用户权限
	public ModelAndView cIQUserAuthority(HttpServletRequest request, HttpServletResponse response) {
		Long id = ControllerHelper.extractId(request);
		Map map = new HashMap();
		User user = getServiceContainer().getUserService().findCIQUserById(id);
		List<UserRightType> allRights = getServiceContainer().getUserService().findAllRightType();
		List<UserRightSpec> userRights = getServiceContainer().getUserService()
				.findUserRightByUserid(user.getId());
		for (UserRightType UserRightType : allRights) {
			for (UserRightSpec userRightSpec : userRights) {
				if (UserRightType.getCode().equals(userRightSpec.getRightCode())) {
					UserRightType.setChecked(true);
				}
			}
		}

		map.put("user", user);
		map.put("rights", allRights);
		return new ModelAndView("CIQUserAuthority.jsp", "map", map);
	}

	// //entuser
	// 创建企业用户
	public ModelAndView entUserCreate(HttpServletRequest request, HttpServletResponse response) {
		EntUser r = new EntUser();
		Map map = new HashMap();
		map.put("user", r);
		return new ModelAndView("EntUserEdit.jsp", "map", map);
	}

	// 查看企业用户
	public ModelAndView entUserView(HttpServletRequest request, HttpServletResponse response) {
		Long id = ((EntUser) ControllerHelper.getUserBySession()).getId();
		Map map = new HashMap();
		map.put("user", getServiceContainer().getUserService().findEntUserById(id));
		return new ModelAndView("EntUserView.jsp", "map", map);
	}

	// 编辑企业用户
	public ModelAndView entUserEdit(HttpServletRequest request, HttpServletResponse response) {
		Long id = ControllerHelper.extractId(request);
		Map map = new HashMap();
		map.put("user", getServiceContainer().getUserService().findEntUserById(id));
		return new ModelAndView("EntUserEdit.jsp", "map", map);
	}

	// 删除企业用户
	public ModelAndView entUserDelete(HttpServletRequest request, HttpServletResponse response) {
		Long id = ControllerHelper.extractId(request);
		getServiceContainer().getUserService().deleteEntUser(id);
		return new ModelAndView(new RedirectView("EntUserSearch.do"));
	}

	// 查看\审核\导出Apply
	public ModelAndView applyCensor(HttpServletRequest request, HttpServletResponse response) {
		Long id = ControllerHelper.extractId(request);
		Apply apply = getServiceContainer().getApplyBizService().findApplyById(id);
		List<ApplyCensor> list = getServiceContainer().getApplyBizService()
				.findApplyCensorByApplyId(id);
		ApplyCensor censor1 = new ApplyCensor();
		ApplyCensor censor2 = new ApplyCensor();
		for (ApplyCensor applyCensor : list) {
			if (applyCensor.getCensorKind() != null && applyCensor.getCensorKind().equals("305")) {
				censor1 = applyCensor;
			}
			if (applyCensor.getCensorKind() != null && applyCensor.getCensorKind().equals("307")) {
				censor2 = applyCensor;
			}
		}

		getServiceContainer().getApplyBizService().getApplyDao().evict(apply);
		getServiceContainer().getApplyBizService().getApplyCensorDao().evict(censor1);
		getServiceContainer().getApplyBizService().getApplyCensorDao().evict(censor2);
		if (apply.getApplyCode() == null || apply.getApplyCode().length() == 0) {
			String s = getServiceContainer().getApplyBizService().findMaxApplyCode();
			long l = Long.parseLong(s);
			l = l + 1;
			apply.setApplyCode(AppConstant.getAppPropValue("applyCodePrefix") + l);
		}

		Map map = new HashMap();
		map.put("opt", request.getParameter("opt"));
		map.put("apply", apply);
		map.put("censor1", censor1);
		map.put("censor2", censor2);

		map.put("applyJson", FormatTransformHelper.bean2json("apply", apply));
		map.put("censor1Json", FormatTransformHelper.bean2json("censor1", censor1));
		map.put("censor2Json", FormatTransformHelper.bean2json("censor2", censor2));

		return new ModelAndView("ApplyCensor.jsp", "map", map);
	}

	// 展品类报检单、货物详单
	public ModelAndView declView(HttpServletRequest request, HttpServletResponse response) {
		Map map = commonDeclView(request);
		map.put("opt", request.getParameter("opt"));
		return new ModelAndView("DeclView.jsp", "map", map);
	}

	// common decl view
	private Map commonDeclView(HttpServletRequest request) {
		Long id;
		if (request.getParameter("id") != null) {
			// by decl id
			id = ControllerHelper.extractId(request);
		} else {
			// by goods id
			id = ControllerHelper.extractId(request, "gid");
			Goods goods = getServiceContainer().getCheckBizService().findGoodsByGoodsId(id);
			Decl decl = getServiceContainer().getCheckBizService().findDeclByDeclNo(
					goods.getDeclNo());
			id = decl.getId();
		}

		// 报检单
		Decl decl = getServiceContainer().getCheckBizService().findDeclById(id);
		// 集装箱
		List<Container> containerList = getServiceContainer().getCheckBizService()
				.findContainerByDecl(decl.getDeclNo());
		// 货物
		List<Goods> goodsList = getServiceContainer().getCheckBizService().findGoodsByDeclNo(
				decl.getDeclNo());
		List<Goods> anchorGoodsList = new ArrayList<Goods>();
		List<Goods> nonAnchorGoodsList = new ArrayList<Goods>();
		for (Goods goods : goodsList) {
			goods.setWoodPackCheck(getServiceContainer().getCheckBizService()
					.findWoodPackCheckByDeclNoGoodsNoSynth(goods.getDeclNo(), goods.getGoodsNo()));
			if (goods.getAnchor() != null && goods.getAnchor().equals(1L)) {
				anchorGoodsList.add(goods);
			} else {
				nonAnchorGoodsList.add(goods);
			}
		}
		// 报检单详细查验信息
		InspResultSum inspResultSum = getServiceContainer().getCheckBizService()
				.findInspResultSumByDecl(decl.getDeclNo());
		// 集装箱结果
		List<ContainerCheck> containerCheckList = getServiceContainer().getCheckBizService()
				.findContainerCheckByDeclNo(decl.getDeclNo());
		// 集装箱疫情
		List<GoodsSituation> containerSituation = getServiceContainer().getCheckBizService()
				.findContainerSituationByDeclNo(decl.getDeclNo());

		// 监管结果
		SupervisePlan supervisePlan = decl.getSupervisePlan();
		if (supervisePlan == null) {
			supervisePlan = getServiceContainer().getCheckBizService().saveSupervisePlanByDeclNo(
					decl);
		}
		decl.setSupervisePlan(supervisePlan);

		Map map = new HashMap();
		map.put("decl", decl);
		map.put("containerList", containerList);
		map.put("anchorGoodsList", anchorGoodsList);
		map.put("nonAnchorGoodsList", nonAnchorGoodsList);
		map.put("inspResultSum", inspResultSum);
		map.put("containerCheckList", containerCheckList);
		map.put("containerSituation", containerSituation);
		return map;
	}

	// 货物详细查验结果
	public ModelAndView goodsCheckInfo(HttpServletRequest request, HttpServletResponse response) {
		Long goodsId = ControllerHelper.extractId(request, "goodsId");
		Map map = new HashMap();
		Goods goods = getServiceContainer().getCheckBizService().findGoodsByGoodsId(goodsId);
		String declNo = goods.getDeclNo();
		Long goodsNo = goods.getGoodsNo();
		map.put("goods", goods);

		GoodsCheck goodsCheck = getServiceContainer().getCheckBizService()
				.findGoodsCheckByDeclNoGoodsNo(declNo, goodsNo);
		List<WoodPackCheck> woodList = getServiceContainer().getCheckBizService()
				.findWoodPackCheckByDeclNoGoodsNo(declNo, goodsNo);
		if (goodsNo.intValue() == 1) {
			woodList.addAll(getServiceContainer().getCheckBizService()
					.findWoodPackCheckByDeclNoGoodsNo(declNo, 0L));
		}
		List<GoodsSituation> poxList = getServiceContainer().getCheckBizService()
				.findGoodsSituationByDeclNoGoodsNo(declNo, goodsNo);

		map.put("goodsCheck", goodsCheck);
		map.put("woodList", woodList);
		map.put("poxList", poxList);

		return new ModelAndView("GoodsCheckInfo.jsp", "map", map);
	}

	// ciq审核核销
	public ModelAndView auditClearList(HttpServletRequest request, HttpServletResponse response) {
		Long id = ControllerHelper.extractId(request);
		Decl decl = getServiceContainer().getCheckBizService().findDeclById(id);
		List<Goods> goodsList = getServiceContainer().getCheckBizService().findClearGoodsByDeclNo(
				decl.getDeclNo());

		List<Goods> applyClearlist = new ArrayList<Goods>();
		List<Goods> alreadyClearlist = new ArrayList<Goods>();
		List<Goods> noClearList = new ArrayList<Goods>();
		for (Goods goods : goodsList) {
			if (goods.getGoodsClearItem() == null
					|| goods.getGoodsClearItem().getClearFlag() == null
					|| goods.getGoodsClearItem().getClearFlag().intValue() < 4) {
				noClearList.add(goods);
			} else if (goods.getGoodsClearItem().getClearFlag().equals(4L)) {
				applyClearlist.add(goods);
			} else if (goods.getGoodsClearItem().getClearFlag().equals(5L)) {
				alreadyClearlist.add(goods);
			}
		}

		Map map = new HashMap();
		map.put("decl", decl);
		map.put("applyClearlist", applyClearlist);
		map.put("alreadyClearlist", alreadyClearlist);
		map.put("noClearList", noClearList);
		return new ModelAndView("AuditClearList.jsp", "map", map);
	}

	// 查看结案报告
	public ModelAndView exhArchiveReport(HttpServletRequest request, HttpServletResponse response) {
		Long id = ControllerHelper.extractId(request);
		Apply apply = getServiceContainer().getApplyBizService().findApplyById(id);
		List<Decl> allDecl = getServiceContainer().getApplyBizService().findDeclByApplyId(
				apply.getId());
		List<Goods> clearGoodsList = getServiceContainer().getApplyBizService()
				.findClearGoodsByApplyIdAnd(apply.getId());

		Map<String, String> inspectDeclMap = new HashMap<String, String>();
		inspectDeclMap.put("pList", getServiceContainer().getApplyBizService()
				.findDeclByApplyIdAndMonitorCondition(apply.getId(), "P"));
		inspectDeclMap.put("qList", getServiceContainer().getApplyBizService()
				.findDeclByApplyIdAndMonitorCondition(apply.getId(), "Q"));
		inspectDeclMap.put("rList", getServiceContainer().getApplyBizService()
				.findDeclByApplyIdAndMonitorCondition(apply.getId(), "R"));
		inspectDeclMap.put("sList", getServiceContainer().getApplyBizService()
				.findDeclByApplyIdAndMonitorCondition(apply.getId(), "S"));
		inspectDeclMap.put("mList", getServiceContainer().getApplyBizService()
				.findDeclByApplyIdAndMonitorCondition(apply.getId(), "M"));
		inspectDeclMap.put("nList", getServiceContainer().getApplyBizService()
				.findDeclByApplyIdAndMonitorCondition(apply.getId(), "N"));
		inspectDeclMap.put("lList", getServiceContainer().getApplyBizService()
				.findDeclByApplyIdAndMonitorCondition(apply.getId(), "L"));
		inspectDeclMap.put("nonList", getServiceContainer().getApplyBizService()
				.findDeclByApplyIdAndMonitorCondition(apply.getId(), null));

		Map map = new HashMap();
		map.put("opt", request.getParameter("opt"));
		map.put("apply", apply);
		map.put("allDecl", allDecl);
		map.put("clearGoodsList", clearGoodsList);
		map.put("inspectDeclMap", inspectDeclMap);

		// ///////////// Json //
		// apply
		map.put("applyJson", FormatTransformHelper.bean2json("apply", apply));
		// inspectDeclList
		map.put("inspectDeclMapJson", FormatTransformHelper.bean2json("map", inspectDeclMap));
		// allDeclList
		List<Decl> simpleDeclList = new ArrayList<Decl>();
		Decl simpleDecl;
		for (Decl decl : allDecl) {
			simpleDecl = new Decl();
			simpleDecl.setDeclNo(decl.getDeclNo());
			simpleDecl.setTradeCountryName(Code2NameHelper.getNameByCode("country", decl
					.getTradeCountryCode()));
			simpleDeclList.add(simpleDecl);
		}

		map.put("simpleDeclListJson", FormatTransformHelper.bean2json("list", simpleDeclList));
		// goodsList
		List<Goods> simpleGoodsList = new ArrayList<Goods>();
		Goods simpleGoods;
		for (Goods goods : clearGoodsList) {
			simpleGoods = new Goods();
			simpleGoods.setDeclNo(goods.getDeclNo());
			simpleGoods.setGoodsCname(goods.getGoodsCname());
			simpleGoods.setInspMonitorCond(goods.getInspMonitorCond());
			simpleGoods.setQty(goods.getQty());
			simpleGoods.setQtyUnitName(Code2NameHelper.getNameByCode("measure", goods
					.getQtyUnitCode()));
			simpleGoods.setWeight(goods.getWeight());
			simpleGoods.setWeightUnitCname(Code2NameHelper.getNameByCode("measure", goods
					.getWeightUnitCode()));
			if (goods.getGoodsClearItem() != null) {
				simpleGoods.setGoodsClearItem(goods.getGoodsClearItem());
				if (goods.getGoodsClearItem().getPassageBills() != null) {
					String s = FormatTransformHelper.getStringFromArray(goods.getGoodsClearItem()
							.getPassageBills().toArray(new PassageBill[0]));
					goods.getGoodsClearItem().setPassageNo(s);
				}
			}

			simpleGoodsList.add(simpleGoods);
		}
		map.put("simpleGoodsListJson", FormatTransformHelper.bean2json("list", simpleGoodsList));
		return new ModelAndView("ExhArchiveReport.jsp", "map", map);
	}

	// //entuser identity
	public ModelAndView entApplyEdit(HttpServletRequest request, HttpServletResponse response) {
		Long id;
		Map map = new HashMap();
		try {
			id = ControllerHelper.extractId(request);
		} catch (Exception e) {
			String tempId = RandomStringUtils.randomAlphabetic(18).toLowerCase();
			map.put("tempId", tempId);
			return new ModelAndView("ApplyEdit.jsp", "map", map);
		}
		Apply apply = getServiceContainer().getApplyBizService().findApplyById(id);
		map.put("apply", apply);
		return new ModelAndView("ApplyEdit.jsp", "map", map);
	}

	public ModelAndView imgUpload(HttpServletRequest request, HttpServletResponse response) {
		String tempId;
		List<UploadFile> files = new ArrayList<UploadFile>();
		Map map = new HashMap<String, Object>();
		tempId = request.getParameter("tempId");
		files = getServiceContainer().getFileBizService().findImgListBytempId(tempId);
		map.put("tempId", tempId);
		map.put("files", files);
		map.put("count", files.size());
		return new ModelAndView("ImgUpload.jsp", "map", map);
	}

	public ModelAndView imgList(HttpServletRequest request, HttpServletResponse response) {
		List<UploadFile> files = new ArrayList<UploadFile>();
		Map map = new HashMap<String, Object>();
		// applyid
		Long id = ControllerHelper.extractId(request);
		files = getServiceContainer().getFileBizService().findImgListById(id);
		map.put("files", files);
		map.put("count", files.size());
		return new ModelAndView("ImgList.jsp", "map", map);
	}


	// 企业核销
	public ModelAndView entGoodsClearList(HttpServletRequest request, HttpServletResponse response) {
		Long id = ControllerHelper.extractId(request);
		Decl decl = getServiceContainer().getCheckBizService().findDeclById(id);
		List<Goods> goodsList = getServiceContainer().getCheckBizService().findClearGoodsByDeclNo(
				decl.getDeclNo());

		List<Goods> noClearlist = new ArrayList<Goods>();
		List<Goods> alreadyClearlist = new ArrayList<Goods>();
		for (Goods goods : goodsList) {
			if (goods.getGoodsClearItem() == null
					|| goods.getGoodsClearItem().getClearFlag() == null
					|| goods.getGoodsClearItem().getClearFlag().intValue() < 4) {
				noClearlist.add(goods);
			} else if (goods.getGoodsClearItem().getClearFlag().intValue() >= 4) {
				alreadyClearlist.add(goods);
			}
		}

		Map map = new HashMap();
		map.put("decl", decl);
		map.put("noClearlist", noClearlist);
		map.put("alreadyClearlist", alreadyClearlist);
		return new ModelAndView("EntGoodsClearList.jsp", "map", map);
	}

	// //////////////////////////////////////////////////////////
	public ModelAndView defaultView(HttpServletRequest request, HttpServletResponse response) {
		return new ModelAndView("");
	}
}
